package com.uddenberg.wt.providers;

import java.util.HashMap;

import com.uddenberg.wt.dbdefinitions.DailyDataDefinition.DailyDataColumns;
import com.uddenberg.wt.dbdefinitions.FoodMealDataDefinition.FoodMealDataColumns;
import com.uddenberg.wt.dbdefinitions.FoodOtherDataDefinition.FoodOtherDataColumns;
import com.uddenberg.wt.dbdefinitions.GeneralDataDefinition.GeneralDataColumns;
import com.uddenberg.wt.dbdefinitions.GeneralDataDefinition;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class GeneralDataProvider extends ContentProvider {
	
	private static final String TAG = "GeneralDataProvider";
	
	private static final String DATABASE_NAME = "general.db";
    private static final int DATABASE_VERSION = 1;
    
    private static HashMap<String, String> sGeneralDataProjectionMap;
    private static final UriMatcher sUriMatcher;
    
    private static final int GENERAL = 1;
    private static final int GENERAL_ID = 2;
    
    /**
     * This creates/opens the database.
     */
    private static class DatabaseOpenHelper extends SQLiteOpenHelper {
        DatabaseOpenHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
 
        @Override
        public void onCreate(SQLiteDatabase db) {
        	 
        	//The columns we'll include in the dictionary table
            db.execSQL("CREATE TABLE general " +
                	"("+GeneralDataColumns._ID+" INTEGER primary key autoincrement, " + 
                	GeneralDataColumns.WELLNESS+" INTEGER DEFAULT 0 NOT NULL," +
                	GeneralDataColumns.STRESS+" INTEGER DEFAULT 0 NOT NULL," +
                	GeneralDataColumns.ENERGY+" INTEGER DEFAULT 0 NOT NULL," +
                	GeneralDataColumns.HAPPINESS+" INTEGER DEFAULT 0 NOT NULL," +
                	GeneralDataColumns.ACTIVITY+" INTEGER DEFAULT 0 NOT NULL," +
                	GeneralDataColumns.FOCUS+" INTEGER DEFAULT 0 NOT NULL," +
                	GeneralDataColumns.VALUE+" INTEGER DEFAULT 0 NOT NULL," +
                	GeneralDataColumns.TIME+" INTEGER DEFAULT 0 NOT NULL);");
            
            
            
            
        }


        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS general;");
            
            
            
            onCreate(db);
        }
    }
    
    private DatabaseOpenHelper mDatabaseOpenHelper;
    
    @Override
    public boolean onCreate() {
    	mDatabaseOpenHelper = new DatabaseOpenHelper(getContext());
        return true;
    }
    
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables("general");

        switch (sUriMatcher.match(uri)) {
        case GENERAL:
            qb.setProjectionMap(sGeneralDataProjectionMap);
            break;

        case GENERAL_ID:
            qb.setProjectionMap(sGeneralDataProjectionMap);
            qb.appendWhere(GeneralDataColumns._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = GeneralDataColumns.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        // Get the database and run the query
        SQLiteDatabase db = mDatabaseOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }
    
    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
        case GENERAL:
            return GeneralDataColumns.CONTENT_TYPE;

        case GENERAL_ID:
            return GeneralDataColumns.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }
    
    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        // Validate the requested uri
        if (sUriMatcher.match(uri) != GENERAL) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        // Make sure that the fields are all set
        if (values.containsKey(GeneralDataColumns.WELLNESS) == false) {
            values.put(GeneralDataColumns.WELLNESS, 0);
        }

        if (values.containsKey(GeneralDataColumns.STRESS) == false) {
            values.put(GeneralDataColumns.STRESS, 0);
        }
        
        if (values.containsKey(GeneralDataColumns.ENERGY) == false) {
            values.put(GeneralDataColumns.ENERGY, 0);
        }
        
        if (values.containsKey(GeneralDataColumns.HAPPINESS) == false) {
            values.put(GeneralDataColumns.HAPPINESS, 0);
        }
        
        if (values.containsKey(GeneralDataColumns.ACTIVITY) == false) {
            values.put(GeneralDataColumns.ACTIVITY, 0);
        }
        
        if (values.containsKey(GeneralDataColumns.FOCUS) == false) {
            values.put(GeneralDataColumns.FOCUS, 0);
        }
        
        if (values.containsKey(GeneralDataColumns.VALUE) == false) {
            values.put(GeneralDataColumns.VALUE, 0);
        }
        
        if (values.containsKey(GeneralDataColumns.TIME) == false) {
            values.put(GeneralDataColumns.TIME, 0);
        }


        SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase();
        long rowId = db.insert("general", GeneralDataColumns.WELLNESS, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(GeneralDataColumns.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }
    
    
    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case GENERAL:
            count = db.delete("general", where, whereArgs);
            break;

        case GENERAL_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.delete("general", GeneralDataColumns._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
    
    @Override
    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
        SQLiteDatabase db = mDatabaseOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case GENERAL:
            count = db.update("general", values, where, whereArgs);
            break;

        case GENERAL_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.update("general", values, GeneralDataColumns._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
    
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(GeneralDataDefinition.AUTHORITY, "general", GENERAL);
        sUriMatcher.addURI(GeneralDataDefinition.AUTHORITY, "general/#", GENERAL_ID);

        sGeneralDataProjectionMap = new HashMap<String, String>();
        sGeneralDataProjectionMap.put(GeneralDataColumns._ID, GeneralDataColumns._ID);
        sGeneralDataProjectionMap.put(GeneralDataColumns.WELLNESS, GeneralDataColumns.WELLNESS);
        sGeneralDataProjectionMap.put(GeneralDataColumns.STRESS, GeneralDataColumns.STRESS);
        sGeneralDataProjectionMap.put(GeneralDataColumns.ENERGY, GeneralDataColumns.ENERGY);
        sGeneralDataProjectionMap.put(GeneralDataColumns.HAPPINESS,GeneralDataColumns.HAPPINESS);
        sGeneralDataProjectionMap.put(GeneralDataColumns.ACTIVITY,GeneralDataColumns.ACTIVITY);
        sGeneralDataProjectionMap.put(GeneralDataColumns.FOCUS,GeneralDataColumns.FOCUS);
        sGeneralDataProjectionMap.put(GeneralDataColumns.VALUE,GeneralDataColumns.VALUE);
        sGeneralDataProjectionMap.put(GeneralDataColumns.TIME,GeneralDataColumns.TIME);

    }
	
}
